package com.winsafe.scanlibrary;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.device.scanner.configuration.Triggering;
import android.os.Handler;

public class UrovoScanner {

    private static boolean mReceiverTag = false;
    private static Context mContext;

    public static final String RES_SCAN_UROVO = "android.intent.ACTION_DECODE_DATA";

    public static ScanManager mScanManager;

    private static BroadcastReceiver mUrovoBroadcastReceiver;
    private static IntentFilter mUrovoIntentFilter;

    public static Handler mHandler;

    public static void init(Context context) {

        try {
            mContext = context;

            mScanManager = new ScanManager();
            mScanManager.switchOutputMode(0);//0： 广播模式   1：键盘模式
            mScanManager.setTriggerMode(Triggering.HOST);//单次扫描
            mScanManager.setPropertyInts(new int[]{PropertyID.SEND_GOOD_READ_BEEP_ENABLE}, new int[]{0});

            /*
             * 初始化意图过滤器：
             * 扫描结果的意图过滤器的动作一定要使用"android.intent.action.SCANRESULT"
             */
            mUrovoIntentFilter = new IntentFilter(RES_SCAN_UROVO);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }


    public static void registerBroadcastReceiver() {
        if (!mReceiverTag && mUrovoIntentFilter != null) {
            mReceiverTag = true;
            mUrovoBroadcastReceiver = new ScanResultReceiver(mHandler);
            mContext.registerReceiver(mUrovoBroadcastReceiver, mUrovoIntentFilter);
//            Log.e(TAG, "registerSeuicBroadcastReceiver");
        }
    }

    public static void unregisterBroadcastReceiver() {
        if (mReceiverTag && mUrovoBroadcastReceiver != null) {
            mReceiverTag = false;
            mContext.unregisterReceiver(mUrovoBroadcastReceiver);
//            Log.e(TAG, "unregisterSeuicBroadcastReceiver");
        }
    }

    public static void startScanning() {
        mScanManager.openScanner();
    }

    public static void stopScanning() {
        mScanManager.closeScanner();
    }

}
